require 'cgi'

class PagesController < ApplicationController
  include Security::Session::Access
  include Utils::Url

  def show 
    @page = Page.find(id_param)
    unless current_user_has_access?(@page.user_group_ids)
      redirect_to(denied_url)
      return
    end
    find_document_categories
  end

  def view_document
    dv = DocumentVersion.find(id_param)
    send_file(dv.name)
  end

  def spell
    cmd = params[:cmd]
    text = params[:check]
    resp = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
    case cmd
    when "spell"
      words = Page.spell_check(text, current_user_id)
      session[:page_check] = words
      data = split_text(words)
      resp += "<res id=\"#{params[:id]}\" cmd=\"#{params[:cmd]}\">#{data}</res>"
    when "suggest"
      data = get_suggestion(text)
      resp += "<res id=\"#{params[:id]}\" cmd=\"#{params[:cmd]}\">#{data}</res>"
    end
    render(:xml => resp)
  end

  private
    def split_text(words)
      text = []
      words.each{|w| text << w[0]}
      text.join("+")
    end

    def get_suggestion(text)
      return unless session[:page_check]
      rvalue = ""
      session[:page_check].each do |words|
        rvalue = words[1].gsub(/, /,"+") if words[0] == text
      end
      rvalue
    end

    def find_document_categories
      @document_categories = []
      @page.document_category.each do |dc|
        @document_categories << dc  if current_user_has_access?(dc.user_group_ids)
      end
    end
end
